function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject();	//xmlhttp holds the ajax object
var responseText = '';
var latestSelectBox= new Object();





function initilaizeForm(){
    getYearMonthList();
    getWeeksInMonth();
    disableSaveClearButtons();
    populateTimeCells();
}
function disableDatePicker(){
    document.getElementById('year').disabled = true;
    document.getElementById('month').disabled = true;
    document.getElementById('week').disabled = true;
}


function populateTimeCells(){
    //
    enableSaveClearButtons();
    var week =  document.getElementById('week').value;
    var queryString=setQueryString();
    sendRequest("GET", "GetTask?"+queryString, getExistingTasks);

    


}

function enableSaveClearButtons(){
    document.getElementById('save').disabled=false;
    document.getElementById('clear').disabled=false;
}

function showTaskRow(){
    var tbl = document.getElementById('taskTable');
    
    disableDatePicker();
    getLabelRow(tbl);
    getFieldrow();
    enableSaveClearButtons();
    
}

function getNewselectBox(){
    var tbl = document.getElementById('taskTable');
    if(xmlhttp) {
        xmlhttp.open("GET","TaskList",false);
        //xmlhttp.onreadystatechange  = handler;
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
        xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
        xmlhttp.send(null);
        responseText = xmlhttp.responseText;
        if(responseText !=null || responseText!=''){
            return makeNewList(responseText);
        }
            
      }

    //sendRequest("GET","TaskList",getTaskList);

   // return selectObj;
}
function checkForblank(){
    alert('checkForblank'+this.name);
    if(this.value == '')
        this.value=0;
    if(this.value>24){
        alert('Please enter a realistic date or Give us your time machine');
        this.focus();
    }


}
function validateTimeCell()
   {
       var timeValue=this.value;
       var c=timeValue.charAt(timeValue.length-1);
      if(!((c >= "0") && (c <= "9"))){
          if(c!= ''){
          alert('Please enter a digit');
          this.value=0;
          this.focus();
          }
          
      }
      timeValue=parseInt(timeValue);
      if(timeValue>24){
          alert('Please enter a realistic date or Give us your time machine');
          this.value=0;
          this.focus();
      }
   }
function getTimeCells(lastRow){
    var tbl = document.getElementById('taskTable');
    var numOfRows = tbl.rows.length;
    //var lastRow =tbl.getElementsByTagName("tr")[numOfRows-1];

    var week = document.getElementById('week').value;
    var weekArr = week.split('-');
    var startDate = parseInt(weekArr[0]);
    var endDate = parseInt(weekArr[1]);
    var numOfDays = (endDate-startDate)+1;

    var newCell;
    var newTimeCell;

    for(var i=1;i<numOfDays+1;i++){
        newCell =lastRow.insertCell(i);
        newTimeCell = document.createElement('input');
        newTimeCell.id = 'time'+numOfRows+i;
        newTimeCell.name = 'time'+numOfRows+i;
        newTimeCell.size = 2;
        newTimeCell.type = 'text';
        newTimeCell.value=0;
        newTimeCell.onkeyup=validateTimeCell;
        newCell.appendChild(newTimeCell);
    }
}

function setLatestSelectBox(selectBox){
    latestSelectBox=selectBox;
    
}

function getLatestSelectBox(){
    setTimeout("alert()", 0);
    return latestSelectBox;
}

function makeNewList(responseText){
    var tbl = document.getElementById('taskTable');
    var lastRow = tbl.rows.length;
    responseText=responseText.replace('\n', '', 'g');
    responseText=responseText.replace('\r', '', 'g');
    if(responseText != '')
        {
            var row = tbl.insertRow(lastRow);
            var selectCell = row.insertCell(0);
            var selectObj = document.createElement('select');
            selectObj.name = 'taskBox'+lastRow;
            selectObj.id = 'taskBox'+lastRow;
            selectCell.appendChild(selectObj);
            var taskArr = responseText.split(':');
            var opt;
            for (var i = 0;i<taskArr.length-1;i++)
                {
                    opt = new Option(taskArr[i],taskArr[i]);
                    selectObj.options[i]=opt;
                }
                //setLatestSelectBox(selectObj);
                getTimeCells(row);
                return selectObj;
        }
        else{
            alert('Please enter a task form the Enter Task page to proceed');
            return false;
        }
}



function getExistingTasks() {
    if (xmlhttp.readyState == 4){
     if(xmlhttp.status == 200) {
         if(xmlhttp.responseText != null || xmlhttp.responseText != 'null' || xmlhttp.responseText != '' || xmlhttp.responseText != 'undefined')
		 {
        var tbl = document.getElementById('taskTable');
        var lastRow = tbl.rows.length;
        getLabelRow(tbl);
        var resTxt =  xmlhttp.responseText;

        var xmlDoc = loadXMLString(resTxt);
        
    if(xmlDoc.getElementsByTagName('tasks')[0]){
         var numOfExistingTasks=xmlDoc.getElementsByTagName("tasks")[0].childNodes.length;
         var taskBox;
        var week = document.getElementById('week').value;
        var weekArr = week.split('-');
        var startDate = parseInt(weekArr[0]);
        var endDate = parseInt(weekArr[1]);
        var numOfDays = (endDate-startDate)+1;
         for(var i=0;i<numOfExistingTasks;i++){
            taskBox=getFieldrow();

            lastRow = tbl.rows.length;
            //taskBox=getLatestSelectBox();
            //taskBox=document.getElementsByName('taskBox'+lastRow)[0];
            
            for(var j=0;j<taskBox.options.length;j++){
                if(taskBox.options[j].value == xmlDoc.getElementsByTagName('task')[i].attributes[0].value)
                    taskBox.options[j].selected = true;
                for(var k=1;k<numOfDays+1;k++){
                    document.getElementById('time'+lastRow+k).value=xmlDoc.getElementsByTagName('task')[i].attributes[k].value;
                }
            }
         }
         }
         else{
             getFieldrow();
         }
      }
	  }
    }disableDatePicker();
}

function getFreshTasks(tbl,numberOfRows){
    var lastSelectBox =document.getElementById('taskBox'+(numberOfRows-1));
    if(lastSelectBox.options.length == 1){
        alert('No more tasks to continue. Please enter new task from the Enter task page and try again.');
        return false;
    }
        
    var row = tbl.insertRow(numberOfRows);//Insert a dumy row so that there's a space bet ween 2 rows
    numberOfRows=numberOfRows+1;
    var currentSelectBox =document.createElement('select');
    currentSelectBox.id='taskBox'+numberOfRows;
    currentSelectBox.name='taskBox'+numberOfRows;
    row = tbl.insertRow(numberOfRows);
    var selectCell = row.insertCell(0);
    selectCell.appendChild(currentSelectBox);
    var currentSelectBoxIndex = 0;
    for(var i=0;i<lastSelectBox.options.length;i++){
        if(lastSelectBox.value != lastSelectBox.options[i].value){
            currentSelectBox.options[currentSelectBoxIndex]= new Option(lastSelectBox.options[i].text,lastSelectBox.options[i].value);
            currentSelectBoxIndex++;
        }
    }
    getTimeCells(row);
    return currentSelectBox;
}
//
//function createTimeCcell(cellName,cellNumber){
//    var resultCell = document.createElement('input');
//    resultCell.name = cellName+cellNumber;
//    resultCell.type = "text";
//    resultCell.size= 2;
//    return resultCell;
//}

function getWeekDay(date){
    var year=document.getElementById('year').value;
    var month = document.getElementById('month').value;

    var d= new Date(year,month,date);
    var day = d.getDay();

    switch(day){
        case 0: return 'Sun';
        case 1: return 'Mon';
        case 2: return 'Tue';
        case 3: return 'Wed';
        case 4: return 'Thu';
        case 5: return 'Fri';
        case 6: return 'Sat';
    }
}

function getLabelRow(tbl){
    var labelRowExists = false;
    if(document.getElementById('labelRow')){
        labelRowExists = true;
    }
    if(!labelRowExists){

        var firstRow = tbl.insertRow(0);
        var cell=firstRow.insertCell(0);
        cell.appendChild(document.createTextNode('Tasks'));
        cell=firstRow.insertCell(1);
        cell.appendChild(document.createTextNode('Days'));

        var lastRow=tbl.rows.length;
        var weekValue = document.getElementById('week').value;
        var weekArray = weekValue.split('-');
        var startDate = parseInt(weekArray[0]);
        var endDate = parseInt(weekArray[1])
        var row1 = tbl.insertRow(lastRow);
        row1.id='labelRow';
        
        cell = row1.insertCell(0);

        var counter=1;
        var currentDate;

        while(startDate<=endDate){
            currentDate=startDate;
            cell = row1.insertCell(counter);
            cell.appendChild(document.createTextNode(currentDate+'/'+getWeekDay(currentDate)));
            cell = null;
            counter++;
            startDate++;
        }
    }
}

function getFieldrow(){
    var tbl = document.getElementById('taskTable');
    var lastRow = tbl.rows.length;

    //Generate the Second row with input & list boxes
    if(document.getElementById('taskBox'+(lastRow-1)))
        return getFreshTasks(tbl,lastRow);
    else{
        return getNewselectBox();
        
    }
}

function prepareSaveData(inForm){
    var tbl = document.getElementById('taskTable');
    var lastRow = tbl.rows.length;
    
    document.getElementById('numOfRows').value = lastRow;

    var queryString=setQueryString();
    var url = "Save?"+queryString;
    sendRequest("GET", url, displaySaveResult);
}

function displaySaveResult(){
    if (xmlhttp.readyState == 4)
    {
     if(xmlhttp.status == 200) {
       document.getElementById('saveResult').innerHTML=xmlhttp.responseText;
     }//Update the HTML Form element
    }
}

function setQueryString(){
    var queryString="";
    var frm = document.forms[0];
    var numberElements =  frm.elements.length;
    for(var i = 0; i < numberElements; i++) {
        if(i < numberElements-1) {
            queryString += frm.elements[i].name+"="+
                           encodeURIComponent(frm.elements[i].value)+"&";
        } else {
            queryString += frm.elements[i].name+"="+
                           encodeURIComponent(frm.elements[i].value);
        }

    }
    return queryString;
}

function getYearMonthList(){
   
    document.getElementById('year').options[0]=new Option('2008','2008');
    document.getElementById('year').options[1]=new Option('2009','2009');
    document.getElementById('year').options[2]=new Option('2010','2010');

    var today = new Date();

    for(var i=0;i<document.getElementById('year').options.length;i++){
        if(document.getElementById('year').options[i].value==today.getYear())
            document.getElementById('year').options[i].selected=true;
    }
//    document.getElementById('month').options[0]=new Option('Jan',0);
//    document.getElementById('month').options[1]=new Option('Feb',1);
//    document.getElementById('month').options[2]=new Option('Mar',2);
//    document.getElementById('month').options[3]=new Option('April',3);
//    document.getElementById('month').options[4]=new Option('May',4);
//    document.getElementById('month').options[5]=new Option('Jun',5);
//    document.getElementById('month').options[6]=new Option('Juk',6);
//    document.getElementById('month').options[7]=new Option('Aug',7);
//    document.getElementById('month').options[8]=new Option('Sep',8);
//    document.getElementById('month').options[9]=new Option('Oct',9);
//    document.getElementById('month').options[10]=new Option('Nov',10);
//    document.getElementById('month').options[11]=new Option('Dec',11);

    var monthArray = new Array('January','February','March','April','May','June','July','August','Septempber','October','November','December');
    for(var i=0;i<monthArray.length;i++){
        document.getElementById('month').options[i]= new Option(monthArray[i],i);
    }

    for(var i=0;i<document.getElementById('month').options.length;i++){
        if(document.getElementById('month').options[i].value==today.getMonth())
            document.getElementById('month').options[i].selected=true;
    }
}


function getWeeksInMonth(){
	var inForm = document.forms[0];
    var firstday = (new Date(inForm.year.value, inForm.month.value, 1)).getDay();
    var numOfDaysInMonth = daysInMonth(inForm.month.value,inForm.year.value);
	var lastday = (new Date(inForm.year.value, inForm.month.value, numOfDaysInMonth)).getDay();
    var numOfWeeks=0;
    
	if(firstday == 0 && inForm.month.value == 1){ // 4 week February
		numOfWeeks = 4;
	}
	else if(firstday < lastday || inForm.month.value == 1){ // Feb never has more than 5 weeks
		numOfWeeks= 5;
	}
	else {
		numOfWeeks =6;
	}

    var a=firstday;
    var firstWeek = true;
    var index=0;
    document.getElementById('week').options.length = 0;
    while(numOfWeeks>0){
        
        if(firstWeek == true){
            document.getElementById('week').options[index]= new Option('1-'+(7-a),'1-'+(7-a));
            a=7-a;
            firstWeek=false;
        }
        else if(numOfWeeks ==1){
            document.getElementById('week').options[index]= new Option((a+1)+'-'+numOfDaysInMonth,(a+1)+'-'+numOfDaysInMonth);
        }else{
            document.getElementById('week').options[index]= new Option((a+1)+'-'+(a+7),(a+1)+'-'+(a+7));
            a=a+7;
        }
        numOfWeeks--;
        index++;
    }
    
}

function daysInMonth(iMonth, iYear)
{
	return 32 - new Date(iYear, iMonth, 32).getDate();
}


function sendRequest(method,url,handler){
    if(xmlhttp) {
        xmlhttp.open(method,url,true);
        xmlhttp.onreadystatechange  = handler;
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
        xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
        xmlhttp.send(null);
      }
}

function getTaskList(){
    if(xmlhttp.readyState ==4){
        if(xmlhttp.status==200){
            responseText = xmlhttp.responseText;
            makeNewList(responseText);
        }
    }

}


function saveNewTaskHandler(){
    if(xmlhttp.readyState == 4){
        if(xmlhttp.status == 200){
            document.getElementById('save_result').innerHTML = xmlhttp.responseText;
        }
    }
}

function enableAnotherTaskButton(){
    document.getElementById('another_task').disabled=false;
}
function SaveNewTask(){
    enableAnotherTaskButton();
    var inputBox=document.getElementById('task_name');
    if(inputBox.value == ''){
        alert('Task cannot be blank. Please enter again');
        inputBox.focus();
        return false;
    }

    var queryString = setQueryString();
    sendRequest("GET","NewTask?"+queryString, saveNewTaskHandler);
}
function enableDatePicker(){
     document.getElementById('year').disabled = false;
    document.getElementById('month').disabled = false;
    document.getElementById('week').disabled = false;
}

function disableSaveClearButtons(){
    document.getElementById('save').disabled=true;
    document.getElementById('clear').disabled=true;
}
function ClearForm(){
    var tbl = document.getElementById('taskTable');
    var lastRow = tbl.rows.length;
    for(var i=lastRow-1;i>=0;i--){
        tbl.deleteRow(i);
    }
    enableDatePicker();
    disableSaveClearButtons();
    document.getElementById('saveResult').innerHTML= '';
}

function loadXMLString(txt)
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(txt);
  return xmlDoc;
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"text/xml");
    return xmlDoc;
    }
  catch(e) {alert(e.message)}
  }
return null;
}

function clearPage(){
    document.getElementById('task_name').value = '';
    document.getElementById('save_result').innerHTML='';
}

function initializeNewTaskForm(){
    document.getElementById('task_name').focus();
    document.getElementById('another_task').disabled=true;
}